package com.zk.iotgateway.controller;

import com.zk.iotgateway.component.FileUploadService;
import com.zk.iotgateway.domain.Msg;
import com.zk.iotgateway.domain.param.IotConfigDO;
import com.zk.iotgateway.domain.param.IotDispatchDO;
import com.zk.iotgateway.service.IotConfigService;
import com.zk.iotgateway.service.IotDispatchService;
import com.zk.iotgateway.util.ResultUtil;
import com.zk.iotgateway.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 *
 * 文件上传controller
 * @author:mn.m
 * @create 2019-04-30 上午 10:25
 **/
@Controller
@RequestMapping("/iot/manager/")
public class IotConfigController {

    private static final Logger  loger= LoggerFactory.getLogger(IotConfigController.class);

    @Autowired
    private IotConfigService iotConfigService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private IotDispatchService iotDispatchService;

    @GetMapping("index")
    public ModelAndView manageIndex(){
        ModelAndView view=new ModelAndView();
        view.setViewName("iot_index");
        return view;
    }


    @GetMapping("list")
    @ResponseBody
    public Msg list(){
        try {
            List<IotConfigDO> list=iotConfigService.findAll();
            return ResultUtil.success(list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.failure();
        }
    }

    @GetMapping("dispatchIndex/{port}")
    public ModelAndView dispatchIndex(@PathVariable String port){
        ModelAndView view=new ModelAndView();
        if (!StringUtils.isEmpty(port)){
            System.out.println(port);
            view.addObject("port",port);
        }
        view.setViewName("dispatch/iot_dispatch_info");
        return view;
    }

    @GetMapping("addIotServer")
    public ModelAndView addIotServer(){
        ModelAndView view=new ModelAndView();
        view.setViewName("server_add");
        return view;
    }


    /*
    *  增加配置
    * com.mn.iotgateway.controller.ClzFileController
    * */
    @PostMapping("add")
    @ResponseBody
    public Msg saveConfig(IotConfigDO iotConfigDO){
  /*      System.out.println(iotConfigDO);*/
        if(iotConfigDO==null){
            return ResultUtil.beanIsNull();
        }
        IotConfigDO configByPort = iotConfigService.findConfigByPort(iotConfigDO.getPort());
        if (configByPort!=null){
            return ResultUtil.cutomfailure("端口"+iotConfigDO.getPort()+"已占用");
        }
        /*
        * 保存表单信息
        * */
        iotConfigDO.setIsOpen("0");
        iotConfigService.addConfig(validField(iotConfigDO));
        return ResultUtil.success();
    }

    /*
    *
    * 批量移除网关
    * */
    @RequestMapping("removeBatch/{ports}")
    @ResponseBody
    public Msg removeBatch(@PathVariable String ports){
        if (!StringUtils.isEmpty(ports)){
            String[] port=ports.split(",");
            for (String item:port) {
                //删除网关及消息分发记录
                iotConfigService.removeConfg(item);
                iotDispatchService.removeByPort(item);
                //删除记录同时删除容器中的mq 和网关
                iotConfigService.shutdown(item);
                iotDispatchService.removeAllMq(item);
            }
            return ResultUtil.customSuccess("成功删除"+port.length+"行记录");
        }
        return ResultUtil.cutomfailure("参数不能为空!");
    }

    @GetMapping("editPage/{port}")
    public ModelAndView editPage(@PathVariable String port){
        ModelAndView view=new ModelAndView();
        if (!StringUtils.isEmpty(port)){
            IotConfigDO iotConfigDO=iotConfigService.findConfigByPort(port);
            view.addObject("iotConfig",iotConfigDO);
        }
        view.setViewName("server_add");
        return view;
    }

    @GetMapping("uploadcls")
    public ModelAndView openlayer(@RequestParam("clspath") String clspath){
        ModelAndView view=new ModelAndView();
        if (!StringUtils.isEmpty(clspath)){
         view.addObject("clspath",clspath);
        }
        view.setViewName("upload_cls");
        return view;
    }

    @PostMapping("update")
    @ResponseBody
    public Msg edit(IotConfigDO iotConfigDO){
        if(iotConfigDO==null){
            return ResultUtil.beanIsNull();
        }
        /*
         * 保存表单信息
         * */
        iotConfigService.editConfig(validField(iotConfigDO));
      /*  iotConfigService.removeConfg(iotConfigDO.getPort());*/
        return ResultUtil.success();
    }

    /*
    * 开启端口
    * */
    @GetMapping("start/{port}")
    @ResponseBody
    public Msg startPort(@PathVariable  String port){
        if (!StringUtils.isEmpty(port)){
            IotConfigDO iot=iotConfigService.findConfigByPort(port);
            String beanName= com.zk.iotgateway.util.StringUtils.getBeanName(iot.getHandler());
            try {
                if (SpringUtil.getBean(beanName)==null){
                    return ResultUtil.cutomfailure("上传类未加载，请重启应用！!");
                }
            }catch (Exception e){
                return ResultUtil.cutomfailure("上传类未加载，请重启应用！!");
            }
            //先开启mq
            List<IotDispatchDO> validByPort = iotDispatchService.findValidByPort(port);
            iotDispatchService.startAllMq(validByPort);
            System.out.println(String.format("！！！网关开始提供终端连接服务，开启端口号为：%s",iot.getPort()));
            boolean flag=iotConfigService.establish(iot);
            if (flag){
                return ResultUtil.customSuccess("端口开启成功！");
            }else{
                ResultUtil.cutomfailure("端口开启失败！!");
            }
        }
        return ResultUtil.cutomfailure("参数不能为空!");
    }

    /*
     * 关闭端口
     * */
    @GetMapping("shutdown/{port}")
    @ResponseBody
    public Msg shutDownPort(@PathVariable  String port){
        if (!StringUtils.isEmpty(port)){
            System.out.println(String.format("！！！网关终止提供终端连接服务，终止端口号为：%s",port));
            boolean flag=iotConfigService.shutdown(port);
            if (flag){
                //从容器中移除
                iotDispatchService.removeAllMq(port);
                return ResultUtil.customSuccess("端口终止成功！");
            }else{
                ResultUtil.failure("端口终止失败！!");
            }
        }
        return ResultUtil.failure("参数不能为空!");
    }

    @PostMapping("/upload")
    @ResponseBody
    public Msg  upload(MultipartFile file,IotConfigDO iotConfigDO) throws Exception {
        System.out.println(iotConfigDO.getClspath());
        System.out.println(file.getSize());
        if (!StringUtils.isEmpty(iotConfigDO.getClspath())&&file!=null){
            fileUploadService.upload(file,iotConfigDO.getClspath());
            return ResultUtil.success(iotConfigDO);
        }
        return ResultUtil.failure();
    }






    private IotConfigDO validField(IotConfigDO iotConfigDO){
        if (StringUtils.isEmpty(iotConfigDO.getBoss())){
            iotConfigDO.setBoss("2");
        }
        if (StringUtils.isEmpty(iotConfigDO.getWork())){
            iotConfigDO.setWork("4");
        }
        if (StringUtils.isEmpty(iotConfigDO.getQueueLength())){
            iotConfigDO.setQueueLength("1024");
        }
        if (StringUtils.isEmpty(iotConfigDO.getAllIdleTime())){
            iotConfigDO.setAllIdleTime("300");
        }
        return iotConfigDO;
    }


}
